package com.aduerr.v1shouyin.mvp.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.OrderGetPosOrderLEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.adpter.stickrecycleadpter;
import com.aduerr.v1shouyin.util.LogUtils;
import com.aduerr.v1shouyin.util.PeixiDividerGridItemDecoration;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 没有使用了
 */
public class RefoundRecordActivity extends AppCompatActivity {

    private int page = 1;
    private RecyclerView recyclerview;
    private com.aduerr.v1shouyin.mvp.adpter.stickrecycleadpter stickrecycleadpter;
    private TextView tv_title;
    private ImageView img_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testactivity);
        tv_title = (TextView) findViewById(R.id.tv_title);
        img_back = (ImageView) findViewById(R.id.img_back);
        tv_title.setText("退款记录");
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false));

        recyclerview.addItemDecoration(new PeixiDividerGridItemDecoration(this,
                PeixiDividerGridItemDecoration.VERTICAL_LIST, 8, R.color.bg_ios));
        stickrecycleadpter = new stickrecycleadpter(this);
        StickyRecyclerHeadersDecoration headersDecor =
                new StickyRecyclerHeadersDecoration(stickrecycleadpter); //绑定之前的adapter

        stickrecycleadpter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                headersDecor.invalidateHeaders();
            }
        });
        recyclerview.addItemDecoration(headersDecor);
        recyclerview.setAdapter(stickrecycleadpter);

//        listView.setAdapter(mAdapter = new BaseRecyclerAdapter<Void>
//        (simple_list_item_2) {
//        @Override
//        protected void onBindViewHolder(SmartViewHolder holder, Void model, int
//        position) {
//            holder.text(android.R.id.text1, String.format(Locale.CHINA, "第%02d条数据",
//            position));
//            holder.text(android.R.id.text2, String.format(Locale.CHINA,
//            "这是测试的第%02d条数据", position));
//            holder.textColorId(android.R.id.text2, R.color.colorTextAssistant);
//        }
//    });

        final RefreshLayout refreshLayout =
                (RefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData(RefoundRecordActivity.this, 1);

//                    mAdapter.refresh(initData());
                        refreshlayout.finishRefresh();
                        refreshlayout.setLoadmoreFinished(false);
                    }
                }, 2000);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        initData(RefoundRecordActivity.this, page);
//                        stickrecycleadpter.loadmore(initData(testactivity.this, page));


                        refreshlayout.finishLoadmore();
//                    if (mAdapter.getItemCount() > 60) {
//                        Toast.makeText(getApplication(), "数据全部加载完毕", Toast
//                        .LENGTH_SHORT).show();
//                        refreshlayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
//                    }
                    }
                }, 2000);
            }
        });

        //触发自动刷新
        refreshLayout.autoRefresh();

    }


    private void initData(Context mContext, int page) {

        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDate = sDateFormat.format(new Date());
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("page", page + "");
        addParams.put("beginDate", "1970-12-08 10:00:00");
        addParams.put("endDate", currentDate);
        addParams.put("state", "6");
//        getView().showProgress();
        APIRetrofit.getAPIService().orderGetPosOrderL(RXRequest.getXingPosParams(addParams, mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderGetPosOrderLEntity>() {


                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull OrderGetPosOrderLEntity orderGetPosOrderLEntity) {
//                        if (Tools.isAvailable(orderGetPosOrderLEntity)) return;
                        int success = orderGetPosOrderLEntity.getSuccess();
                        if(success == 1) {
                            int PageCount = orderGetPosOrderLEntity.getPageCount();
                            int PageIndex = orderGetPosOrderLEntity.getPageIndex();

                            LogUtils.e("PageCount",
                                    "================================" + PageCount);
                            LogUtils.e("pageIndex",
                                    "================================" + PageIndex);
                            List<OrderGetPosOrderLEntity.DataBean> data =
                                    orderGetPosOrderLEntity.getData();
                            if(data.size() > 0) {
                                if(PageIndex > 1) {
                                    LogUtils.e("loadmore",
                                            "================================" + data.size());
                                    stickrecycleadpter.loadmore(data);
                                } else {
                                    LogUtils.e("refresh",
                                            "================================" + data.size());
                                    stickrecycleadpter.refresh(data);
                                }
                            } else {
                                ToastUtils.showToast(RefoundRecordActivity.this, "没有数据了");
                            }
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(RefoundRecordActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(RefoundRecordActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(RefoundRecordActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(orderGetPosOrderLEntity.getErrMsg());
                            SharedPreferencesUtils.remove(RefoundRecordActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(RefoundRecordActivity.this,
                                    "remberpassword");
                            //// TODO: 2017/12/9 0009 去登录的界面
                            startActivity(new Intent(RefoundRecordActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {
                            ToastUtils.showToast(RefoundRecordActivity.this,
                                    orderGetPosOrderLEntity.getErrMsg() + "");
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(mContext, "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(mContext, "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(mContext, "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
}
